﻿using Microsoft.AspNetCore.Hosting;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace ST.Common.Util
{
    public class EnvironmentHelper
	{
		private readonly IWebHostEnvironment hostingEnvironment;

		public EnvironmentHelper(IWebHostEnvironment _hostingEnvironment)
		{
			hostingEnvironment = _hostingEnvironment;
		}

		/// <summary>
		/// 获取静态文件放置的目录（即默认的wwwroot目录）
		/// </summary>
		/// <returns></returns>
		public string GetWebRootPath()
		{
			return hostingEnvironment.WebRootPath;
		}

		/// <summary>
		/// 获取应用程序的根目录
		/// </summary>
		/// <returns></returns>
		public string GetContentRootPath()
		{
			return hostingEnvironment.ContentRootPath;
		}

		/// <summary>
		/// 获取应用程序的根目录
		/// </summary>
		/// <returns></returns>
		public static string GetCurrentDirectory()
		{
			var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
			var pathToContentRoot = Path.GetDirectoryName(pathToExe);
			return pathToContentRoot;
		}

		/// <summary>
		/// 映射路径
		/// </summary>
		/// <param name="path">服务器端路径如：~/bin</param>
		/// <returns>映射后的路径如：e:\app\bin</returns>
		public static string MapPath(string path)
		{
			//not hosted. For example, run in unit tests
			string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
			path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
			return Path.Combine(baseDirectory, path);
		}

		/// <summary>
		/// 获取本机IP地址
		/// </summary>
		/// <returns></returns>
		public static async Task<string> GetLocalIPAsync()
		{
			string localIP = (await Dns.GetHostAddressesAsync(Dns.GetHostName()).ConfigureAwait(false))
				 .Where(x => x.AddressFamily == AddressFamily.InterNetwork)
				 .Select(x => x.ToString())
				 .FirstOrDefault();
			return localIP;
		}

		/// <summary>
		/// 获取本机IP地址
		/// </summary>
		/// <returns></returns>
		public static string GetLocalIP()
		{
			string localIP = Dns.GetHostAddresses(Dns.GetHostName()).Where(x => x.AddressFamily == AddressFamily.InterNetwork)
				 .Select(x => x.ToString())
				 .FirstOrDefault();
			return localIP;
		}
	}
}
